﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace ProjetoFase2
{
    public partial class ListenForm : Form
    {
        // delegate to access combobox
        delegate void BindComboBoxCallback();

        private int port;
        private TcpListener listener;
        private Socket traineeSocket;
        private Thread listenThread;
        private NetworkStream stream;
        private DataSet traineeDataSet;
        private UserLogin userLogin;

        public ListenForm(string ipa, int port, UserLogin userLogin)
        {
            InitializeComponent();

            panelRes.Visible = false;

            btnSync.Enabled = false;

            this.Text += " - " + userLogin.Username;

            this.port = port;

            this.userLogin = userLogin;
            //IPAddress ipAdrr = IPAddress.Parse(ipa);
            listener = new TcpListener(port);
            listener.Start();

            traineeDataSet = new DataSet();

            listenThread = new Thread(new ThreadStart(Listen));
            listenThread.Start();
        }

        private void BindComboBox()
        {
            btnSync.Enabled = true;
            panelRes.Visible = true;

            cmbResidence.DataSource = traineeDataSet.Tables["residence"];
            cmbResidence.DisplayMember = "address";
            cmbResidence.ValueMember = "resi_id";
            txtTopology.DataBindings.Add("Text", cmbResidence.DataSource, "topology");
            cmbCooling.DataBindings.Add("SelectedIndex", cmbResidence.DataSource, "cooling");
            cmbHeating.DataBindings.Add("SelectedIndex", cmbResidence.DataSource, "heating");
            cmbIsolation.DataBindings.Add("SelectedIndex", cmbResidence.DataSource, "isolation");
            cmbCoverage.DataBindings.Add("SelectedItem", cmbResidence.DataSource, "coverage");
            cmbGlasses.DataBindings.Add("SelectedItem", cmbResidence.DataSource, "glasses");
            cmbApproved.DataBindings.Add("SelectedIndex", cmbResidence.DataSource, "approved");
            cmbResidence_SelectedIndexChanged(null, null);

        }
        
        private void Listen()
        {
            ServerInteraction servInt = new ServerInteraction(null, 0);

            try
            {
                traineeSocket = listener.AcceptSocket();

                if (traineeSocket.Connected)
                {
                    stream = new NetworkStream(traineeSocket);

                    // get the trainee supervisor's id
                    string supId = servInt.readString(stream);

                    if (supId == userLogin.Username)
                    {
                        // write ok info
                        servInt.writeString(stream, "valid");

                        traineeDataSet = servInt.readDataSet(stream);
                        if (this.cmbResidence.InvokeRequired)
                        {
                            BindComboBoxCallback bindBox = new BindComboBoxCallback(BindComboBox);
                            this.Invoke(bindBox);
                        }
                        else
                        {
                            BindComboBox();
                        }

                    }
                    else
                    {
                        servInt.writeString(stream, "invalid");
                        MessageBox.Show("The trainee that tried to connect is not supervised by you!");
                        menuClose_Click(null, null);
                    }

                }
            }
            catch (Exception) { }
            
        }

        private void menuClose_Click(object sender, EventArgs e)
        {
            listener.Stop();
            this.Close();
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            btnSync.Enabled = false;

            ServerInteraction servInt = new ServerInteraction(null, 0);

            if (traineeSocket.Connected)
            {
                // send data back to trainee
                traineeDataSet.AcceptChanges();
                servInt.writeDataSet(stream, traineeDataSet);
                this.Close();
            }

            try
            {
                btnSync.Enabled = true;
            }
            catch (Exception) { }
        }

        private void cmbResidence_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                cmbCoolingSup.SelectedIndex = 0;
                cmbHeatingSup.SelectedIndex = 0;
                cmbIsolationSup.SelectedIndex = 0;
                cmbCoverageSup.SelectedIndex = 0;
                cmbGlassesSup.SelectedIndex = 0;
                txtTopologySup.Text = "";

                DatabaseConnector dbCon = new DatabaseConnector(userLogin.Username, userLogin.Password);
                Residence auxResi = dbCon.selectResidence("inactive", (int)cmbResidence.SelectedValue);

                if (auxResi != null)
                {

                    cmbCoolingSup.SelectedIndex = auxResi.Cooling;
                    cmbHeatingSup.SelectedIndex = auxResi.Heating;
                    cmbIsolationSup.SelectedIndex = auxResi.Isolation;
                    cmbCoverageSup.SelectedIndex =
                        (auxResi.Coverage == "Telhado" ? 1 : (auxResi.Coverage == "Placa" ? 2 :
                        (auxResi.Coverage == "Piso Superior" ? 3 : 0)));
                    cmbGlassesSup.SelectedIndex =
                        (auxResi.Glasses == "Simples" ? 1 : (auxResi.Glasses == "Duplos" ? 2 : 0));
                    txtTopologySup.Text = auxResi.Topology;
                }
            }
            catch(Exception) {}
        }

    }
}